package com.obrempon.credit.market.ui.fragment

import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.obrempon.credit.market.R
import com.obrempon.credit.market.common.CommonFragment
import com.obrempon.credit.market.configs.ObremponApiPath
import com.obrempon.credit.market.configs.ObremponApiUrl
import com.obrempon.credit.market.configs.ObremponApiUrl.addCommonParams
import com.obrempon.credit.market.databinding.ObremponAuthStepWalletAccountFragmentBinding
import com.obrempon.credit.market.event.ObremponEventData
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.request.IHttpCallback
import com.obrempon.credit.market.ui.activity.ObremponAuthStepsAct
import com.obrempon.credit.market.ui.adapter.ObremponAuthStepWalletAccountApt
import com.obrempon.credit.market.ui.dialog.ObremponWalletAccountAddDialog
import com.obrempon.credit.market.ui.dialog.ObremponWalletAccountBindOtherDialog
import com.obrempon.credit.market.ui.dialog.ObremponWalletAccountCompleteDialog
import com.obrempon.credit.market.ui.dialog.ObremponWalletAccountDeleteDialog
import com.obrempon.credit.market.ui.dialog.ObremponWalletAccountSubmitOnlyOneDialog
import com.obrempon.credit.market.utils.helper.ObremponConfigsHelper
import org.json.JSONObject

/**
 * ObremponCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/20 10:38
 * @Annotation：认证流程 - 法语地区绑定账户
 */
class ObremponAuthStepWalletAccountFragment(): CommonFragment() {
    lateinit var binding: ObremponAuthStepWalletAccountFragmentBinding
    private var stepItem: JSONObject? = null
    private var eventRemark = ""

    private var walletAdapter: ObremponAuthStepWalletAccountApt? = null

    constructor(stepItem: JSONObject): this(){
        eventRemark = stepItem.optString("stepTitle")
        this.stepItem = stepItem
    }

    override fun getObremponRootView(inflater: LayoutInflater): View {
        binding = ObremponAuthStepWalletAccountFragmentBinding.inflate(inflater)
        return binding.root
    }

    override fun initObremponView() {
        initObremponWalletAccountListView()
    }

    override fun initObremponListener() {
        //添加
        binding.walletAccountAdd.setOnClickListener {
            showObremponWalletAccountAddDialog()
        }

        //提交
        binding.walletAccountNext.setOnClickListener {
            if (!isObremponWalletAccountSubmit()){
                showErrorTipsDialog(getString(R.string.obrempon_dialog_tips_submit_error), eventRemark)
                return@setOnClickListener
            }
            onObremponWalletAccountCheckSubmitStatus()
        }
    }

    override fun takeObremponData() {
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_STEP_ACCOUNT_START)
        loadObremponWalletAccountListAction()
    }

    /**
     * 初始化Views
     */
    private fun initObremponWalletAccountListView(){
        binding.walletAccountListView.isNestedScrollingEnabled = false
        binding.walletAccountListView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.walletAccountListView.layoutManager = layoutManager
        walletAdapter = ObremponAuthStepWalletAccountApt(binding.walletAccountListView)
        binding.walletAccountListView.adapter = walletAdapter!!
        binding.walletAccountListView.itemAnimator = DefaultItemAnimator()
        walletAdapter?.setOnItemChildClickListener { _, childView, position ->
            val item = walletAdapter!!.getItem(position)
            when(childView.id){
                R.id.walletEdit -> {//添加
                    showObremponWalletAccountAddDialog()
                }
                R.id.walletDelete -> {//删除
                    showObremponWalletAccountDeleteDialog(item)
                }
            }
        }
    }

    /**
     * 已绑定账户列表
     */
    private fun showObremponWalletAccountList(accountList: ArrayList<JSONObject>) {
        walletAdapter?.data = accountList

        //是否可提交
        var isEnabled = false
        for (i in 0..< walletAdapter!!.itemCount){
            val item = walletAdapter?.getItem(i)
            if (!item!!.optBoolean("isEdit",false)){
                isEnabled = true
            }
        }
        binding.walletAccountNext.isEnabled = isEnabled
        //最多添加10个账户
        binding.walletAccountAdd.isEnabled = walletAdapter!!.itemCount < 10
    }

    /**
     * 添加绑卡dialog
     */
    private fun showObremponWalletAccountAddDialog(){
        addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_USER_ACCOUNT_ADD,eventRemark)
//        onIntent(ObremponAuthAccountCreateAct::class.java)
        val bindCardDialog = ObremponWalletAccountAddDialog(requireContext(),eventRemark,object : ObremponWalletAccountAddDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
            override fun onSubmitParams(typeObj: JSONObject, phoneNumber: String) {
                onObremponSumbitAuthStepWalletAddAction(phoneNumber,typeObj.optString("value"))
            }
        })
        bindCardDialog.setCancelable(true)
        bindCardDialog.setCanceledOnTouchOutside(false)
        bindCardDialog.show()
    }

    /**
     * 提示绑定另一个账号
     */
    fun showObremponWalletAccountOtherDialog(otherInfo: JSONObject) {
        val bindOtherDialog = ObremponWalletAccountBindOtherDialog(requireContext(),eventRemark,object : ObremponWalletAccountBindOtherDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.buttonWalletOtherConfirm){//添加
                    onObremponSumbitAuthStepWalletAddAction(otherInfo.optString("walletMobile"),otherInfo.optString("value"), "YES")
                }
            }
        })
        bindOtherDialog.setCancelable(true)
        bindOtherDialog.setCanceledOnTouchOutside(false)
        bindOtherDialog.show()
        bindOtherDialog.showObremponWalletAccountInfo(otherInfo)
    }

    /**
     * 只有一个账户警告提示
     */
    private fun showObremponWalletAccountSubmitOnlyOneWarningDialog(){
        val submitOnlyOneDialog = ObremponWalletAccountSubmitOnlyOneDialog(requireContext(),eventRemark,object : ObremponWalletAccountSubmitOnlyOneDialog.IDialogCallback{
            override fun onClick(view: View?) {
                when(view!!.id){
                    R.id.buttonWalletWarningNoMore -> {//提交(不再有账户)
                        // TODO: 发送通知，更新主流程
                        val act = getAct() as ObremponAuthStepsAct
                        act.showObremponAuthStepSubmitSuccess()
                    }
                    R.id.buttonWalletWarningAdd -> {//继续添加
                        showObremponWalletAccountAddDialog()
                    }
                }
            }
        })
        submitOnlyOneDialog.setCancelable(true)
        submitOnlyOneDialog.setCanceledOnTouchOutside(true)
        submitOnlyOneDialog.show()
    }

    /**
     * 确认dialog
     */
    private fun showObremponWalletAccountConfirmDialog(){
        val submitDialog = ObremponWalletAccountCompleteDialog(requireContext(),object : ObremponWalletAccountCompleteDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.buttonWalletAccountConfirm){
                    addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_USER_ACCOUNT_SUBMIT_TIPS_CONFIRM,"")
                    // TODO: 发送通知，更新主流程
                    val act = getAct() as ObremponAuthStepsAct
                    act.showObremponAuthStepSubmitSuccess()
                }
            }
        })
        submitDialog.show()
        submitDialog.showObremponCompleteWalletAccountList(walletAdapter!!.data)
    }

    /**
     * 删除提示
     */
    private fun showObremponWalletAccountDeleteDialog(item: JSONObject){
        addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_USER_ACCOUNT_DELETE,item.optString("id"))
        val deleteDialog = ObremponWalletAccountDeleteDialog(requireContext(),eventRemark, object : ObremponWalletAccountDeleteDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.walletAccountDeleteConfirm){
                    onObremponDeleteWalletAccountAction(item.optString("id"))
                }
            }
        })
        deleteDialog.setCancelable(true)
        deleteDialog.setCanceledOnTouchOutside(true)
        deleteDialog.show()
        deleteDialog.showObremponWalletAccountInfo(item)
    }

    /**
     * 提交按钮是否可点
     */
    private fun isObremponWalletAccountSubmit(): Boolean{
        //提交按钮是否可点
        var submitIsEnabled = false
        for (i in 0..<walletAdapter!!.itemCount){
            //存在一个不是编辑状态的item，则可以提交
            if (!walletAdapter!!.getItem(i).optBoolean("isEdit",true)){
                submitIsEnabled = true
                break
            }
        }
        return submitIsEnabled
    }

    /**
     * 检查提交
     */
    private fun onObremponWalletAccountCheckSubmitStatus(){
        var count = 0
        walletAdapter?.data?.forEach {
            //不是编辑类型
            if (!it.optBoolean("isEdit",true)){
                count += 1
            }
        }
        //只有一个账户，需要提示
        if (count <= 1){
            showObremponWalletAccountSubmitOnlyOneWarningDialog()
            return
        }
        //预览所有账户列表
        showObremponWalletAccountConfirmDialog()
    }

    override fun onObremponPublishEvent(event: ObremponEventData) {
        super.onObremponPublishEvent(event)
        //刷新已添加账户列表
        if (event.eventType == ObremponEventData.TYPE.OBREMPON_WALLET_REFRESH){
            loadObremponWalletAccountListAction()
        }
    }

    /**
     * 获取已绑定的账户列表
     */
    private fun loadObremponWalletAccountListAction() {
        showObremponLoading()
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", ObremponApiPath.OBREMPON_PATH.OBREMPON_API_ACCOUNT_LIST_FRENCH_PATH)
        }
        doPostAction(httpUrl, params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val array = data.optJSONArray("obj")
                val accountList = arrayListOf<JSONObject>()

                if (array != null && array.length() > 0) {
                    for (i in 0..<array.length()) {
                        val item = array.optJSONObject(i)
                        item.put("isEdit", false)
                        accountList.add(item)
                    }
                }

                if (accountList.size < 2) {
                    for (i in 0..<2 - accountList.size) {
                        val item = JSONObject()
                        item.put("isEdit", true)
                        accountList.add(item)
                    }
                }
                showObremponWalletAccountList(accountList)
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    /**
     * 添加绑卡
     */
    private fun onObremponSumbitAuthStepWalletAddAction(mobile: String, walletChannel: String, bindFlag:String = "NO"){
        showObremponLoading()
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", ObremponApiPath.OBREMPON_PATH.OBREMPON_API_ACCOUNT_ADD_PATH)
            put("walletMobile", mobile)
            put("walletMobileConfirm", mobile)
            put("walletChannel", walletChannel)
            put("addBindFlag", bindFlag)
        }

        doPostAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                //刷新列表
                loadObremponWalletAccountListAction()
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj") ?: JSONObject()
                        // "YES/NO 是否需要提示用户这个号码可以绑另一个渠道的钱包"
                        val addBindFlag = obj.optString("addBindFlag")
                        if (addBindFlag == "YES") {
                            //需要提示绑定另一个渠道账户
                            var otherAccountInfo: JSONObject? = null

                            //用于从APP配置中获取（walletChannels）对应的信息
                            val channel = obj.optString("channel")
                            if (channel.isNotBlank()) {
                                val customize = ObremponConfigsHelper.takeObremponConfigData()
                                if (customize != null) {
                                    val walletChannels = customize.optJSONArray("walletChannels")
                                    if (walletChannels != null && walletChannels.length() > 0) {
                                        for (i in 0..<walletChannels.length()) {
                                            val item = walletChannels.optJSONObject(i)
                                            if (channel == item.optString("value")) {
                                                otherAccountInfo = item
                                                break
                                            }
                                        }
                                    }

                                    // 只有非空的情况下才处理
                                    if (otherAccountInfo != null) {
                                        otherAccountInfo.put("walletMobile", mobile)
                                        //提示绑定另一个渠道账户
                                        showObremponWalletAccountOtherDialog(otherAccountInfo)
                                        return
                                    }
                                }
                            }
                        } else {
                            hideObremponLoading()
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        showObremponToast(msg)
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    /**
     * 删除账户
     */
    fun onObremponDeleteWalletAccountAction(ids: String) {
        showObremponLoading()
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", ObremponApiPath.OBREMPON_PATH.OBREMPON_API_ACCOUNT_DELETE_PATH)
            put("ids", ids)
        }
        doPostAction(httpUrl, params, object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                showObremponToast(data.optString("msg"))
                //刷新列表
                loadObremponWalletAccountListAction()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_STEP_ACCOUNT_END)
    }
}